"use client";
import { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogDescription,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import SubmitButton from "@/components/SubmitButton";
import { useToast } from "@/components/ui/use-toast"
const EditorModal = ({ children,trigger, title, onSubmit,confirmButton="保存",onSuccess   }) => {
  const [open, setOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState(null);

  const { toast } = useToast();


  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);
    setError(null);
    // 这里打印不出来，但是提交到 server action 是可以拿到的？
    const formData = new FormData(e.target);
    const formDataObj = Object.fromEntries(formData.entries());
    const submitRes = await onSubmit(formDataObj);
    console.log('submitRes',submitRes);
    setIsSubmitting(false);
    if(onSuccess && typeof onSuccess === 'function' && submitRes.success){
      onSuccess(submitRes);
    }
    if(!submitRes.success){
      //截断错误信息，避免过长
      setError(submitRes.message.substring(0, 100));
      return;
    }
    if(submitRes.type === "warning"){
      toast({
        variant: "destructive",
        title: "温馨提示",
        description: submitRes.message,
      })
    }
    setOpen(false);
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>{trigger}</DialogTrigger>
      <DialogContent className="w-11/12 sm:max-w-md">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          <DialogDescription>
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit}>
          {children}
          {error && <p className="text-[12px] text-red-500 mt-2 mb-2">{error}</p>}
          <DialogFooter className="gap-4 mt-4">
            <Button type="button" onClick={() => setOpen(false)} variant="outline" disabled={isSubmitting}>
              取消
            </Button>
            <SubmitButton title={confirmButton} isSubmitting={isSubmitting} />
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
};

export default EditorModal;